﻿function ViewModel() {
    var self = this;

    self.appTitle = 'phonecat';
    self.orderProps = ko.observableArray(['Alphabetical', 'Newest']);
    self.orderProp = ko.observable(self.orderProps()[0]);
    self.searchQuery = ko.observable('');
    self.phones = ko.observableArray([]);
    self.phone = ko.observable({});
    self.currentView = ko.observable('list');
    self.mainImageUrl = ko.observable('');


    self.setImage = function(imgUrl) {
        if (imgUrl === self.mainImageUrl())
            return;

        $('#mainImage').fadeOut(function() {
            self.mainImageUrl(imgUrl);
            $('#mainImage').fadeIn();
        });
    };

    self.filteredPhones = ko.computed(function() {
        var filteredPhones = [];
        ko.utils.arrayForEach(self.phones(), function(phone) {
            if (phone.name.toLowerCase().indexOf(self.searchQuery().toLowerCase()) >= 0) {
                filteredPhones.push(phone);
            }
        });
        filteredPhones.sort(function(a, b) {
            if (self.orderProp() === 'Alphabetical') {
                if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
                if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
                return 0;
            } else {
                return a.age - b.age;
            }
        });
        return filteredPhones;
    });


    self.orderProp.subscribe(function() {
        window.location = '#phones';
    });

    self.searchQuery.subscribe(function() {
        window.location = '#phones';
    });


    $.ajax({
        url: 'phones/phones.json',
        success: function(data) {
            self.phones(ko.utils.parseJson(data));
        }
    });

    Sammy(function() {
        this.get('#phones', function() {
            $('#details').fadeOut(function() {
                self.currentView('list');
                $('#list').fadeIn();
            });
        });

        this.get('#phones/:id', function() {
            $.ajax({
                url: 'phones/' + this.params.id + '.json',
                success: function(data) {
                    data = ko.utils.parseJson(data);

                    $('#list').fadeOut(function() {
                        self.phone(data);
                        self.mainImageUrl(data.images[0]);
                        self.currentView('details');
                        $('#details').fadeIn();
                    });
                }
            });
        });

        this.get('', function() {
            this.app.runRoute('get', '#phones');
        });
    }).run();
}

var vm = new ViewModel();
$(function() {
    ko.applyBindings(vm, document.getElementById("topHtml"));
});